package com.jd.org.service.Impl;

import com.jd.basic.service.impl.BaseServiceImpl;
import com.jd.basic.util.Md5Utils;
import com.jd.basic.util.StrUtils;
import com.jd.org.domain.Employee;
import com.jd.org.mapper.EmpMapper;
import com.jd.org.service.IEmpService;
import com.jd.user.domain.Logininfo;
import com.jd.user.mapper.LogininfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service

public class EmpServiceImpl extends BaseServiceImpl<Employee> implements IEmpService {

    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private EmpMapper empMapper;

    @Override
    @Transactional
    public void save(Employee employee) {
        // 获取盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
        // 保存logininfo
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(employee,logininfo);
        logininfo.setType(0);
        logininfo.setDisable(true);
        logininfoMapper.save(logininfo);
        employee.setLogininfo_id(logininfo.getId());
        super.save(employee);
        if(employee.getRoleId()!=null){
            empMapper.addEmployeeRole(employee);
        }
    }

    @Override
    @Transactional
    public void update(Employee employee) {
        //通过empId删除中间表数据 - 外键挂链要注意
        empMapper.delEmployeeRoleByEmpId(employee.getId());

        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = Md5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);

        // 获取登录的id
        Long logininfoId = empMapper.loadById(employee.getId()).getLogininfo_id();
        Logininfo logininfo = logininfoMapper.loadById(logininfoId);
        // copy覆盖
        BeanUtils.copyProperties(employee,logininfo);
        logininfoMapper.update(logininfo);


        //再添加员工的角色信息到中间表：employee - eid roleId
        if(employee.getRoleId()!=null){
            empMapper.addEmployeeRole(employee);
        }
        super.update(employee);
    }

    @Override
    @Transactional
    public void remove(Long id) {
        //通过empId删除中间表数据 - 外键挂链要注意
        empMapper.delEmployeeRoleByEmpId(id);
        // 删除
        Employee employee = empMapper.loadById(id);
        logininfoMapper.remove(employee.getLogininfo_id());
        super.remove(id);
    }

    @Override
    public List<Employee> findByShopId(Long shopId) {
        return empMapper.findByShopId(shopId);
    }
}
